<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas</title>
    <style></style>
  </head>
  <body>
    <div class="container">
      <canvas id="demo"></canvas>
    </div>

    <script>
      ;(function () {
        const $canvas = document.querySelector('#demo')
        $canvas.width = 600
        $canvas.height = 600
        $canvas.style.border = '1px solid #cccccc'

        const context = $canvas.getContext('2d')

        function drawXY() {
          // 坐标的原点位置
          const x0 = 100
          const y0 = 400

          // 坐标最大高度（算 y 轴比值用）
          const maxHeight = 300
          // 箭头宽度
          const arrowWith = 10

          // 绘制 x 轴
          context.beginPath()
          context.strokeStyle = 'blue'
          context.moveTo(x0, y0)
          context.lineTo(500, 400)

          // 画箭头
          // 从 x 轴末端，往斜上和斜下画
          context.lineTo(500 - arrowWith, 400 - arrowWith)
          context.moveTo(500, 400)
          context.lineTo(500 - arrowWith, 400 + arrowWith)
          context.stroke()

          // 绘制 y 轴
          context.beginPath()
          context.strokeStyle = 'orange'
          context.moveTo(x0, y0)
          context.lineTo(100, 0)
          context.lineTo(100 - arrowWith, arrowWith)
          context.moveTo(100, 0)
          context.lineTo(100 + arrowWith, arrowWith)
          context.stroke()

          // 绘制线段
          const data = [0.4, 0.5, 0.8, 0.7]
          // 算出 x 轴度量值（段数要加上原点到第一个值的一段，所以是 data.lenght+1）
          pointWidth = 400 / (data.length + 1)
          context.beginPath()
          context.strokeStyle = 'green'
          for (let index = 0; index < data.length; index++) {
            const x = x0 + (index + 1) * pointWidth
            // y 轴方向向下，所以是 减去
            const y = y0 - data[index] * maxHeight
            context.lineTo(x, y)
          }

          context.stroke()
        }

        drawXY()
      })()
    </script>
  </body>
</html>
